package com.xatime.auth.core;

import com.xatime.auth.core.model.User;
import org.springframework.beans.BeanUtils;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.DefaultAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by mason on 18-12-9.
 */
public class JwtAccessTokenEnhanceConverter extends JwtAccessTokenConverter {

    private final String enhanceName = "user";

    JwtAccessTokenEnhanceConverter() {
        ((DefaultAccessTokenConverter)getAccessTokenConverter())
                .setUserTokenConverter(new JwtUserAuthenticationConverter(enhanceName));
    }

    @Override
    public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
        User user = new User();
        BeanUtils.copyProperties(authentication.getPrincipal(), user, "password", "authorities");
        Map<String, Object> map = new HashMap<>();
        map.put(enhanceName, user);
        ((DefaultOAuth2AccessToken)accessToken).setAdditionalInformation(map);
        return super.enhance(accessToken, authentication);
    }
}
